package com.zhiyou100.service;
import java.util.Date;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.zhiyou100.dao.UserDao;
import com.zhiyou100.exception.LoginException;
import com.zhiyou100.model.User;
import com.zhiyou100.util.DateUtil;
import com.zhiyou100.util.RandomUtil;
import com.zhiyou100.util.SMSUtil;
@Service

public class UserServiceImpl implements UserService{
	@Autowired
	private UserDao userDao;
	public User selectResult(String phone) {
		User user= userDao.selectResult(phone);
		
		if(DateUtil.drationFromNowTo(user.getCodeSendTime())<60) {
			
			throw new LoginException(403001,"抱歉，一分钟之内只能发送一条短信");
		}
		
		int code = RandomUtil.randomNum();
		
		try {
			SMSUtil.sendSMS(phone, code);
		} catch (ServerException e) {
			e.printStackTrace();
		} catch (ClientException e) {
			throw new LoginException(403008,"短信發送失敗，請稍後再試");
		}
		user.setPhone(phone);
		user.setCodeSendTime(new Date());
		user.setCode(code);
		
		if(user!=null) {
			
			userDao.update(user);
		} 
			userDao.add(user);
		
		return user;
	}

	public User loginByCode(User user) {
		User savedUser = userDao.selectLogin(user.getPhone());
		if(savedUser==null) {
			throw new LoginException(403002, "手机号输入有误");
		}
		if(DateUtil.drationFromNowTo(user.getCodeSendTime())>300) {
			throw new LoginException(403003,"验证码失效");
		}
		if(savedUser.getCode().equals(user.getCode())) {
			throw new LoginException(403004,"验证码输入有误");
		}
		if(savedUser.getName()==null) {
			String name = RandomUtil.randomName();
			savedUser.setName(name);
			userDao.updateName(savedUser);
		}
		
		return savedUser;
	}

	public User loginByPassword(User user) {
		User savedUser=userDao.search(user.getPhone());
		if(savedUser==null) {
			 throw new LoginException(403005, "账号不存在"); 
		}
		if(savedUser.getPassword()==null) {
		throw new LoginException(403006,"密码不存在");
		
		}
		if(!savedUser.getPassword().equals(user.getPassword())) {
		throw new LoginException(403007, "密码错误")	;
		}
		
		return savedUser;
		
	}

	public User selectAll(String phone) {
		return userDao.searchAll(phone);
	}

	public void updateAll(User user) {

		userDao.updateAll(user);
	}

	public void updatePassword(User user) {

		userDao.updatePassword(user);
	}

}
